package dao.impl;

import java.util.List;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import org.springframework.stereotype.Repository;

import pojo.TestUser;
import dao.TestUserDao;

@Repository(value="testUserDaoImpl")
public class TestUserDaoImpl implements TestUserDao {
	
	@Resource(name="entityManagerFactory")
	EntityManagerFactory factory = Persistence.createEntityManagerFactory("punit");
	
	EntityManager manager;
	EntityTransaction transaction;
	
	public TestUserDaoImpl() {
		manager = factory.createEntityManager();
		transaction = manager.getTransaction();
	}

	@Override
	public TestUser add(TestUser u) {
		transaction.begin();
		manager.persist(u);
		transaction.commit();
		return u;
	}

	@Override
	public TestUser load(String uname, String passwd) {
		List<?> result = manager.createQuery(
				"SELECT u FROM TestUser u WHERE u.uname = :uname AND u.passwd = :passwd")
				.setParameter("uname", uname)
				.setParameter("passwd", passwd)
				.getResultList();
		return result.isEmpty() ? null : (TestUser) result.get(0);
	}

}
